import React, { Component } from 'react'

export default class List extends Component {
  state = {
    hoverID: '',
  }
  onCheckClick = (item, index) => {
    this.props.onCheckClick && this.props.onCheckClick(item, index)
  }

  handleDelete = (item, index) => {
    this.props.onDelete && this.props.onDelete(item, index)
  }

  handleMouseOver = (item) => {
    this.setState({
      hoverID: item.id,
    })
  }
  handleMouseLeave = (item) => {
    this.setState({
      hoverID: '',
    })
  }

  getListItem = () => {
    let list = this.props.list || []
    return list.map((item, index) => {
      return (
        <li
          key={item.id}
          onMouseOver={() => {
            this.handleMouseOver(item)
          }}
          onMouseLeave={() => {
            this.handleMouseLeave(item)
          }}
        >
          <input
            type="checkbox"
            checked={item.done}
            name={item.name}
            onChange={() => {
              this.onCheckClick(item, index)
            }}
          ></input>
          {item.name}
          {this.state.hoverID === item.id ? (
            <button
              onClick={() => {
                this.handleDelete(item, index)
              }}
            >
              删除
            </button>
          ) : (
            ''
          )}
        </li>
      )
    })
  }

  render() {
    return <ul>{this.getListItem()}</ul>
  }
}
